package com.scx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scx.dto.GoodsSalesDTO;
import com.scx.entity.Orders;
import com.scx.entity.User;
import com.scx.mapper.OrderMapper;
import com.scx.mapper.UserMapper;
import com.scx.service.ReportService;
import com.scx.service.UserService;
import com.scx.service.WorkspaceService;
import com.scx.vo.*;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();   //时间
        List<Double> turnoverList = new ArrayList<>();  //营业额

        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //统计每天营业额
//            QueryWrapper<Orders> qw = new QueryWrapper<>();
//            qw.select("sum(amount) as turnover");
//            qw.eq("status", Orders.COMPLETED);
//            qw.ge("delivery_time",beginTime).le("delivery_time",endTime);
//            Map<String, Object> map = orderMapper.selectMaps(qw).get(0);
//            if(map != null && !map.isEmpty()) {
//                BigDecimal turnoverBD = (BigDecimal) map.get("turnover");
//                double turnover = turnoverBD.doubleValue();
//                turnoverList.add(turnover);
//            }else{
//                turnoverList.add(0.0);
//            }
            //更推荐手写sql
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .turnoverList(StringUtil.join(",", turnoverList))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();   //时间
        List<Integer> totalUserList = new ArrayList<>();  //总用户
        List<Integer> newUserList = new ArrayList<>();  //新增用户
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //统计数量，也可以使用手写的countByMap
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.le(User::getCreateTime, endTime);
            Integer totalUser = userMapper.selectCount(lqw);
            totalUserList.add(totalUser);

            lqw.ge(User::getCreateTime, beginTime);
            Integer newUser = userMapper.selectCount(lqw);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .newUserList(StringUtil.join(",", newUserList))
                .totalUserList(StringUtil.join(",", totalUserList))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();   //时间
        List<Integer> orderCountList = new ArrayList<>();  //订单数集合(下单就算)
        List<Integer> validOrderCountList = new ArrayList<>();  //有效订单数集合(下单且状态为完成)

        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
            lqw.ge(Orders::getOrderTime, beginTime).le(Orders::getOrderTime, endTime);
            Integer orderCount = orderMapper.selectCount(lqw);
            orderCountList.add(orderCount);
            lqw.eq(Orders::getStatus, Orders.COMPLETED);
            Integer validOrderCount = orderMapper.selectCount(lqw);
            validOrderCountList.add(validOrderCount);
        }

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (validOrderCount > 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .orderCountList(StringUtil.join(",", orderCountList))
                .validOrderCountList(StringUtil.join(",", validOrderCountList))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtil.join(",", nameList))
                .numberList(StringUtil.join(",", numberList))
                .build();
    }

    @Override
    public void export(HttpServletResponse response){
        LocalDateTime begin = LocalDate.now().minusDays(30).atStartOfDay();
        LocalDateTime end = LocalDate.now().minusDays(1).atTime(LocalTime.MAX);

        //根据模板获取excel
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = null;
        try {
            excel = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        XSSFSheet sheet = excel.getSheet("Sheet1");

        sheet.getRow(1).getCell(1).setCellValue(begin.toLocalDate() + " 至 " + end.toLocalDate());

        //概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());

        int rowNumber = 7;
        for (LocalDateTime time = begin; time.isBefore(end); time = time.plusDays(1), rowNumber++) {
            LocalDateTime timeEnd = time.toLocalDate().atTime(LocalTime.MAX);
            businessData = workspaceService.getBusinessData(time, timeEnd);

            row = sheet.getRow(rowNumber);
            row.getCell(1).setCellValue(String.valueOf(time.toLocalDate()));
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }
        //通过输出流将文件下载到客户端浏览器中
        try {
            excel.write(response.getOutputStream());
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
